//
//  HWAddressManagementController.m
//  HWanGame
//
//  Created by 陈道斌 on 2019/10/21.
//  Copyright © 2019 Chendaobin. All rights reserved.
//

#import "HWAddressManagementController.h"
#import "HWEditAddressViewController.h"
#import "HWNewAddressViewController.h"
#import<CommonCrypto/CommonDigest.h>
#import "HWAddressSelectCell.h"
#import "HWSetupModel.h"
@interface HWAddressManagementController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate>
@property(strong,nonatomic) UITableView *mainaTableVie;
@property(strong,nonatomic) UIView *lowerPartView;
@property(strong,nonatomic) NSMutableArray *dataArray;



@end

@implementation HWAddressManagementController

- (void)viewWillAppear:(BOOL)animated
{
//    self.navigationController.navigationBarHidden = YES;
    //    [self.tabBarController.tabBar setHidden:YES];

    self.navigationController.delegate = self;
    
}
- (void)navigationController:(UINavigationController*)navigationController willShowViewController:(UIViewController*)viewController animated:(BOOL)animated{ if([[viewController class]isSubclassOfClass:[self class]]) {
    ///执行刷新操作
    //    [self initWithViews];
    //    [self configRequest];
    [self configRequest];
}
    ///删除代理，防止该controller销毁后引起navigationController.delegate指向野指针造成崩溃
    if(![[viewController class]isSubclassOfClass:[self class]]) {
        self.navigationController.delegate=nil;
    }
}



-(UITableView *)mainaTableVie {

    if  (!_mainaTableVie) {

        _mainaTableVie = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _mainaTableVie.contentSize = CGSizeMake(0, _mainaTableVie.frame.size.height);

        
    }
    return   _mainaTableVie ;
    

}








- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configRequest];
    [self setupUI];
    
}

// 设置UI
- (void)setupUI {
     NSString  *dizhi =  [HWjianzhiduiObject keylocalization:@"地址管理"];
    self.navigationItem.title = dizhi;
    self.mainaTableVie.delegate = self;
    self.mainaTableVie.dataSource = self;
    
    
    self.mainaTableVie.backgroundColor = [UIColor whiteColor];
    self.mainaTableVie.estimatedRowHeight = 0;
    self.mainaTableVie.estimatedSectionFooterHeight = 0;
    self.mainaTableVie.estimatedSectionHeaderHeight = 0;
    self.mainaTableVie.rowHeight = UITableViewAutomaticDimension;
    self.mainaTableVie.separatorInset = UIEdgeInsetsMake(0, 1000, 0, 0);
    
    
    [self.mainaTableVie registerClass:[HWAddressSelectCell class] forCellReuseIdentifier:@"HWAddressSelectCell"];
    [self.view addSubview:self.mainaTableVie];
    [self addLowerPartView];
    
    [self.mainaTableVie mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top);
        make.left.mas_equalTo(self.view.mas_left);
        make.height.mas_equalTo(kScreenH-44-CF_TabbarSafeBottomMargin);
        make.width.mas_equalTo(SCREEN_WIDTH);
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return  self.dataArray.count;
    
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    static NSString *cellID = @"cellID";
    
    
    HWAddressSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HWAddressSelectCell" forIndexPath:indexPath];
    cell.backgroundColor  = [UIColor whiteColor];
    cell.selectionStyle  = UITableViewCellSelectionStyleNone;
    [cell.edit addTarget:self action:@selector(editAction:event:) forControlEvents:UIControlEventTouchUpInside];

    if (self.dataArray) {
        HWMallGoogsAddressModel *model = self.dataArray[indexPath.row];

        cell.model = model;
    }

    
    
    return cell;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
   
    
    return 71*CFLScaleValue;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
      HWMallGoogsAddressModel *model = self.dataArray[indexPath.row];
  
     if ([self.panduanStr isEqualToString:@"1"]) {
         
          [self.delegate xuanzhongModel:model];
         
          [self.navigationController popViewControllerAnimated:YES];
        
     }
    
    
    
    
}
// 添加低部UIview
- (void)addLowerPartView {
    
    self.lowerPartView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenH-44-CF_TabbarSafeBottomMargin, kScreenW, 44+CF_TabbarSafeBottomMargin)];
    // self.lowerPartView.backgroundColor = [UIColor yellowColor];
    self.lowerPartView.backgroundColor = RGB(241, 242, 244);
    [self.view addSubview:self.lowerPartView];
    
    
    NSString *xingzen = [HWjianzhiduiObject keylocalization:@"新增地址"];
    
    UIButton *butt  = [UIButton setButtonWithFrame:CGRectMake(15, 4, kScreenW-30, 36) Title:xingzen Image:nil Font:14 Color:RGB(255, 255, 255) Target:self Selector:@selector(buttonTap)];
    butt.backgroundColor = blueBackgroundBT;
    butt.layer.cornerRadius = 18;
    butt.layer.masksToBounds = YES;
    butt.backgroundColor = [UIColor bm_colorGradientChangeWithSizeView:butt];
    [self.lowerPartView addSubview:butt];
    

    
    
    
}






//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    
//    
//    
//}



#pragma  mark   --------- 地址管理
- (void)buttonTap {
    
    HWNewAddressViewController *newAddress = [[HWNewAddressViewController alloc]init];
    [self.navigationController pushViewController:newAddress animated:YES];
    
    
    
}

- (void)configRequest {
    [SVProgressHUD show];
    
    
    
    __weak typeof(self) weakSelf = self;
    
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];
    NSString *timeSp = [NSString stringWithFormat:@"%.0f", time];
    
    
    NSString *sign = @"fsd213ewdsadqwe2121213edsad";
    
    
    
    
    
    
    NSDictionary *parameters = @{
                                 @"ct" : @"app",
                                 @"ac" : @"my_address",
                                 @"uid" : [HWLocallyStoredData getLoginUserID],
                                 @"t" : timeSp,
                                 @"sign" : [self md5:[NSString stringWithFormat:@"%@%@%@", [HWLocallyStoredData getLoginUserID], timeSp, sign]],
                                 };
    
    [HWWebUtils doGetWithParameters:parameters progress:nil success:^(id response) {
        
        [SVProgressHUD dismiss];
        if ([response[@"code"] integerValue] == 1) {
            
            
            [MBProgressHUD showSuccess:response[@"message"]];
            NSLog(@"数据：%@", response);
            self.dataArray = [NSMutableArray array];
            NSArray *arrFirst = [HWMallGoogsAddressModel mj_objectArrayWithKeyValuesArray:response[@"data"]];
            for (HWMallGoogsAddressModel *user in arrFirst) {
                
                [weakSelf.dataArray addObject:user];
                [weakSelf.mainaTableVie reloadData];
            }
            
            
        } else {
            
            [MBProgressHUD showError:response[@"message"]];
            
        }
        
        
    } failure:^(NSString *error) {
        [SVProgressHUD dismiss];
    }];
    
    
}

- (NSString *) md5:(NSString *) input {
    
    const char *cStr = [input UTF8String];
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
    
}

// 修改地址
- (void)editAction:(UIButton *)btn event:(UIEvent *)event {
    
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint point = [touch locationInView:self.mainaTableVie];
    NSIndexPath *indexPath = [self.mainaTableVie indexPathForRowAtPoint:point];
    HWMallGoogsAddressModel *model = self.dataArray[indexPath.row];
    HWEditAddressViewController *edit = [[HWEditAddressViewController alloc] init];
    edit.name = model.consignee;
    edit.mobile = model.mobile;
    edit.uaddress = model.uaddress;
    
    edit.xingming = model.bank_user;
     edit.zhanghaostr = model.bank_id;
    if (model.bank_user  == nil ) {
        edit.xingming =@"";
        edit.zhanghaostr = @"";
           
    }
    
   
    edit.Id = model.Id;
    [self.navigationController pushViewController:edit animated:YES];
}



// 删除地址


-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];
    NSString *timeSp = [NSString stringWithFormat:@"%.0f", time];
    
    
    NSString *sign = @"fsd213ewdsadqwe2121213edsad";
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (indexPath.row<[self.dataArray count]) {
            HWMallGoogsAddressModel *model = self.dataArray[indexPath.row];
            NSDictionary *parameters = @{
                                         @"ct" : @"app",
                                         @"ac" : @"address_del",
                                         @"t" : timeSp,
                                         @"uid" : model.uid,
                                         @"id" : model.Id,
                                         @"sign" : [WMUtil md5HexDigest:[NSString stringWithFormat:@"%@%@%@", model.uid, timeSp, sign]],
                                         };
            
            [HWWebUtils doGetWithParameters:parameters progress:nil success:^(id response) {
                [SVProgressHUD dismiss];
                if ([response[@"code"] intValue] == 1) {
                    [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                    // 先删除数据源
                    [self.dataArray removeObjectAtIndex:indexPath.row];
                    // 再删除cell
                    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];//移除tableView中的数据
                    
                } else {
                    [SVProgressHUD showErrorWithStatus:response[@"messahe"]];
                }
            } failure:^(NSString *error) {
                [SVProgressHUD dismiss];
                [SVProgressHUD showErrorWithStatus:error ? error : @"删除失败"];
            }];
        }
    }
}

@end
